package com.woniu.petkonwledge.service.impl;

import com.woniu.common.entity.QuestionBank;
import com.woniu.petkonwledge.mapper.QuestionBankMapper;
import com.woniu.petkonwledge.service.QuestionBankService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Service
public class QuestionBankServiceImpl implements QuestionBankService {
    @Autowired
    QuestionBankMapper questionBankMapper;
    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<QuestionBank> getQuestion() {
        Random random = new Random();
        List<QuestionBank> questionBanks = new ArrayList<>();
        if (redisTemplate.hasKey("questionBank")) {
            List<Object> list = redisTemplate.opsForList().range("questionBanks", 1, 11);
            for (int i = 0; i < 10; i++) {
                questionBanks.add((QuestionBank) list.get(random.nextInt(list.size())));//随机获取元素
            }
            System.out.println("redis");
        } else {
            List<QuestionBank> questionBanks1 = questionBankMapper.getQuestion();

            redisTemplate.opsForList().rightPushAll("questionBanks",questionBanks1);
            for (int i = 0; i < 10; i++) {
                questionBanks.add(questionBanks1.get(random.nextInt(questionBanks1.size())));//随机获取元素
            }
            System.out.println("数据库");
        }
        return questionBanks;
    }
    @Override
    public QuestionBank getQuestionById(Integer id) {
        return questionBankMapper.getQuestionById(id);
    }
}
